<?php

namespace app\upgrade\api;

use app\one_api\api\ApiInit;
use app\upgrade\model\UpgradeVersion;
use app\upgrade\model\UpgradeFile;
use app\member\model\Login;
use app\upgrade\model\UpgradeWeb;
use app\member\model\Member;
use app\upgrade\model\UpgradeMd5Log;
use app\news\model\Msg as MsgModel;

class Upgrade extends ApiInit
{
    public function initialize()
    {
        parent::initialize();
        $this->UpgradeVersion = new UpgradeVersion;
        $this->UpgradeFile = new UpgradeFile;
        $this->UpgradeWeb = new UpgradeWeb;
        $this->Login = new Login;
        $this->Member = new Member;
        $this->UpgradeMd5Log = new UpgradeMd5Log;
        $this->MsgModel = new MsgModel;
    }
    /**
     * 入口授权
     * d 域名 u 是否删除 m 文件md5列表
     * md5 u system/admin/Upgrade
     *     a one_api/api/ApiInit
     *     c extend/one/Cloud
     *     p thinkphp//library/think/App
     * 返回内容 
     *     u md5不对是否删除文件
     *     m md5是否比对成功
     *     d 是否已认证
     * @param [type] $domain
     * @param [type] $version
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function filemd5()
    {
        $data = $this->params;
        if (!isset($data['m']) || !isset($data['d'])) {
            return $this->_error('非法');
        }
        if (empty($data['m']) || empty($data['d'])) {
            return $this->_success('非法', [
                'u' => (int)0,
                'm' => (int)0,
                'd' => (int)0
            ]);
        }
        // 校验md5
        $md5 = 1;
        if ($data['m']['u'] !== config("cloud.upgrade_md5")) {
            $md5 = 0;
        } else if ($data['m']['a'] !== config("cloud.api_md5")) {
            $md5 = 0;
        } else if ($data['m']['c'] !== config("cloud.cloud_md5")) {
            $md5 = 0;
        } else if ($data['m']['p'] !== config("cloud.app_md5")) {
            $md5 = 0;
        }
        // 查询是否已审核
        $status = $this->UpgradeWeb->getFieldByDomain($data['d'], 'status');
        return $this->_success('获取成功', [
            'u' => (int)config("cloud.unlink_file"),
            // 'm' => 1,  // 临时不校验md5
            'm' => (int)$md5,
            'd' => (int)($status ? $status : 0)
        ]);
    }
    public function log()
    {
        $data = $this->params;
        if (!isset($data['m']) || !isset($data['d'])) {
            return $this->_error('非法');
        }
        if (empty($data['m']) || empty($data['d'])) {
            return $this->_success('非法', [
                'u' => (int)0,
                'm' => (int)0,
                'd' => (int)0
            ]);
        }
        $this->UpgradeMd5Log->save([
            'domain' => $data['d'],
            'info' => serialize($data['i']),
        ]);
    }
    /**
     * 校验绑定状态及版本情况
     *
     * @param [type] $domain
     * @param [type] $version
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function connection()
    {
        $data = $this->params;
        if (!isset($data['domain']) || !isset($data['version']) || !isset($data['branch'])) {
            return $this->_error('非法');
        }
        // 查询是否注册过
        $code = $this->UpgradeWeb->getFieldByDomain($data['domain'], 'id');
        // 查询是否已审核
        $status = $this->UpgradeWeb->getFieldByDomain($data['domain'], 'status');
        // 比对版本
        $update = $this->UpgradeVersion->version_compare($data['version'], $data['branch'], true);

        // 更新该站点版本号
        $cache = cache('update_version_' . md5($data['domain']));
        // 10分钟更新一次，并且是最新版本
        if (!$cache && !$update) {
            $web_info = $this->UpgradeWeb->where(['domain' => $data['domain']])->find();
            if (!$web_info) {
                return $this->_success('获取成功', [
                    'upgrade' => $update ? 1 : 0,
                    'code' => $code ? 1 : 0,
                    'approve' => 0
                ]);
            }
            $web_info->version = $data['version'];
            $web_info->save();
            cache('update_version_' . md5($data['domain']), 1, 600);
        }

        return $this->_success('获取成功', [
            'upgrade' => $update ? 1 : 0,
            'code' => $code ? 1 : 0,
            'approve' => $status ? $status : 0
        ]);
    }
    /**
     * 绑定平台
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function bind()
    {
        $data = $this->params;
        $result = $this->Login->login($data);
        if ($result === false) {
            return $this->_error($this->Login->getError());
        }
        return $this->_success('success', $result);
    }
    /**
     * 注册平台
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function register()
    {
        $data = $this->params;
        if (!isset($data['account']) || !isset($data['password'])) {
            return $this->_error('非法');
        }
        $user['username'] = $data['account'];
        $user['password'] = $data['password'];
        if ($this->Member->getFieldByUsername($data['account'], 'id')) {
            return $this->_error('您已注册过该帐号，请直接登录，若忘记密码，请联系管理员');
        }
        $result = $this->Login->register($user, $data);
        if ($result === false) {
            return $this->_error($this->Login->getError());
        }
        return $this->_success('success', $result);
    }

    /**
     * 获取版本列表
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getVersionList()
    {
        $data = $this->params;
        if (!isset($data['version']) || !isset($data['branch'])) {
            return $this->_error('非法');
        }
        $result = $this->UpgradeVersion->version_compare($data['version'], $data['branch'], true);
        if (false === $result) {
            return $this->_error('获取版本信息失败');
        }
        // $tmp = [];
        // foreach ($result as $key=>$val) {
        //     $tmp[$val['version']] = $val;
        // }
        // $result = $tmp;
        return $this->_success('获取成功', $result);
    }
    /**
     * 获取指定版本文件流
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function downpack()
    {
        $data = $this->params;
        if (!isset($data['version']) || !isset($data['branch'])) {
            return $this->_error('非法');
        }
        $_versions = $this->UpgradeVersion->version_compare($data['version'], $data['branch']);
        if (false === $this->UpgradeFile->download($_versions['file_id'])) {
            return $this->_error($this->UpgradeFile->getError());
        }

        return $this->_success('success', $_versions);
    }
    
    public function getPost() {
        $map = [];
        $map[] = ['status', 'eq', 1];
        $data = $this->MsgModel->where($map)->order('create_time desc')->find();
        return $this->_success('success', $data);
    }
}
